package com.happy_hao.topbiz.realm;

import com.happy_hao.topbiz.po.Permission;
import com.happy_hao.topbiz.po.User;
import com.happy_hao.topbiz.util.RealmUtil;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class FormRealm extends AuthorizingRealm {

    @Resource
    RealmUtil realmUtil;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<Permission> permissions = new HashSet<>(user.getPermissions());
        Set<String> permission = permissions.stream()
                .map(Permission::getPermissionName)
                .collect(Collectors.toSet());

        info.setRoles(permission);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = realmUtil.getUserByMap(token.getUsername());
        if (user == null) {
            throw new UnknownAccountException();
        }
        DefaultPasswordService defaultPasswordService = new DefaultPasswordService();
        if (!defaultPasswordService.passwordsMatch(token.getPassword(), user.getPassword())) {
            throw new IncorrectCredentialsException("用户名或密码错误");
        }
        return new SimpleAuthenticationInfo(user, token.getPassword(), getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
